package cn.wh.xwm.hibernate.dao;

import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;

import cn.wh.xwm.common.util.Constant;

/**
 * A data access object (DAO) providing persistence and search support for
 * Customerinfo entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see cn.wh.xwm.hibernate.dao.Customerinfo
 * @author MyEclipse Persistence Tools
 */

public class CustomerinfoDAO extends BaseHibernateDAO {
	private static final Log log = LogFactory.getLog(CustomerinfoDAO.class);
	// property constants
	public static final String NAME = "name";
	public static final String LEVEL = "level";
	public static final String IS_DISTRICT = "isDistrict";
	public static final String DEFINE_ID = "defineId";
	public static final String VALID = "valid";

	public void save(Customerinfo transientInstance) {
		log.debug("saving Customerinfo instance");
		try {
			getSession().save(transientInstance);
			//保存客户的时候需要保存它相关的产品库存，并设置库存为0
			ProductinfoDAO pdao = new ProductinfoDAO();
			InventoryinfoDAO idao = new InventoryinfoDAO();
			Inventoryinfo iinfo;
			InventoryinfoId id;
			List<Productinfo> list = pdao.findAll();
			for(Productinfo info :list){
				iinfo = new Inventoryinfo();
				id = new InventoryinfoId();
				id.setCustomerId(transientInstance.getId());
				id.setProductId(info.getId());
				iinfo.setId(id);
				iinfo.setInventoryNumber(0);
				idao.save(iinfo);
			}
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Customerinfo persistentInstance) {
		log.debug("deleting Customerinfo instance");
		try {
			//删除客户的时候需要删除它相关的产品库存
			ProductinfoDAO pdao = new ProductinfoDAO();
			InventoryinfoDAO idao = new InventoryinfoDAO();
			Inventoryinfo iinfo;
			InventoryinfoId id;
			List<Productinfo> list = pdao.findAll();
			for(Productinfo info :list){
				id = new InventoryinfoId();
				id.setCustomerId(persistentInstance.getId());
				id.setProductId(info.getId());
				iinfo = idao.findById(id);
				idao.delete(iinfo);
			}
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Customerinfo findById(java.lang.String id) {
		log.debug("getting Customerinfo instance with id: " + id);
		try {
			Customerinfo instance = (Customerinfo) getSession().get(
					"cn.wh.xwm.hibernate.dao.Customerinfo", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Customerinfo instance) {
		log.debug("finding Customerinfo instance by example");
		try {
			List results = getSession().createCriteria(
					"cn.wh.xwm.hibernate.dao.Customerinfo").add(
					Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Customerinfo instance with property: "
				+ propertyName + ", value: " + value);
		try {
			String queryString = "from Customerinfo as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}

	public List findByLevel(Object level) {
		return findByProperty(LEVEL, level);
	}

	public List findByIsDistrict(Object isDistrict) {
		return findByProperty(IS_DISTRICT, isDistrict);
	}

	public List findByDefineId(Object defineId) {
		return findByProperty(DEFINE_ID, defineId);
	}

	public List findByValid(Object valid) {
		return findByProperty(VALID, valid);
	}

	public List findAll() {
		log.debug("finding all Customerinfo instances");
		try {
			String queryString = "from Customerinfo";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Customerinfo merge(Customerinfo detachedInstance) {
		log.debug("merging Customerinfo instance");
		try {
			Customerinfo result = (Customerinfo) getSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Customerinfo instance) {
		log.debug("attaching dirty Customerinfo instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Customerinfo instance) {
		log.debug("attaching clean Customerinfo instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void update(Customerinfo info) {
		log.debug("update Customerinfo instance");
		try {
			getSession().update(info);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
		
	}
	
	
	public String findTotalBysql(String q_customername, String q_customerlevel) {
		String presql = "select count(*) from snfims.customerinfo where 1=1 ";
		if (q_customername != null && !q_customername.trim().equals("")) {
			presql = presql + "and name like '%" + q_customername + "%' ";
		}
		if (q_customerlevel != null && !q_customerlevel.trim().equals("")) {
			presql = presql + "and level = '" + q_customerlevel + "' ";
		}
		return this.findTotalBysql(presql);
	}

	public List<Customerinfo> findByPrame(String page, String row, String q_customername,
			String q_customerlevel) {
		String prehql = "from Customerinfo as model where 1=1 ";
		if (q_customername != null && !q_customername.trim().equals("")) {
			prehql = prehql + "and model.name like '%" + q_customername + "%' ";
		}
		if (q_customerlevel != null && !q_customerlevel.trim().equals("")) {
			prehql = prehql + "and model.level = '" + q_customerlevel + "' ";
		}
		Query queryObject = getSession().createQuery(prehql);

		if (row == null || row.trim().equals("")) {
			row = Constant.ROWLIMIT;
		}
		if (page == null|| page.trim().equals("")) {
			page = Constant.FIRSTPAGE;
		}
		int ipage = Integer.valueOf(page);
		int irow = Integer.valueOf(row);
		int offset = (ipage - 1) * irow;
		queryObject.setFirstResult(offset);
		queryObject.setMaxResults(irow);
		return queryObject.list();
	}
	
	public List<Customerinfo> findNotLevel4(){
		String prehql = "from Customerinfo as model where model.level <> '"+Constant.CUSTOMERLEVEL_4+"' ";
		Query queryObject = getSession().createQuery(prehql);
		return queryObject.list();
	}
}